﻿module Sustainalytics.Controversies {

    import Company = Sustainalytics.Company;
    import Common = Sustainalytics.Common;

    export class QualitativePerformanceController {

        private controversiesCtrl: ControversiesController;
        private esgCtrl: Sustainalytics.EsgRatings.EsgController;

        public controversyIndicators: ControversyIndicatorDto[];
        public controversyIndicatorsDic: Common.Dictionary<ControversyIndicatorDto[]> = new Common.Dictionary<ControversyIndicatorDto[]>();        
        public isControversyActive: boolean;
        public hasControversyClaim:boolean;
        private userId: string;

        private location: any;

        //public notFoundMessage: string ='';
        //public noClaims: boolean = false;

        constructor(
            private $rootScope: ng.IScope,
            private $scope: Company.ICompanyBasedScope,
            private $q: ng.IQService,
            private $timeout: ng.ITimeoutService,
            private $filter: ng.IFilterService,
            private RoutingService: Routing.IRoutingService,
            private ControversiesService: IControversiesService,
            private CompanyService: Company.CompanyService) {

            var ctx = this;

            console.log('QualitativePerformanceController');

            ctx.esgCtrl = $scope['esg'];
            ctx.controversiesCtrl = $scope['controversies'];

            ctx.location = ctx.RoutingService.getRouteEngineAdapter().getCurrentPath();

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            ctx.init();
        }

        private init(): ng.IPromise<any> {
            var ctx = this;

            var promiseIndicators = ctx.getControversyIndicators();
            ctx.getControversiesFeatureUniverse(ctx.$scope.currentCompany.id);
            ctx.getControversyClaim();
            return promiseIndicators;
        }

        private getControversyClaim(): void {
            var ctx = this;
            var controvercyRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'GET', resource: 'api/v1/company/{companyId}/esgControversyIndicator', parameters: [] });
            var controvercyPromise = ctx.RoutingService.validateRouteSecurity(controvercyRouteSecurity);
            controvercyPromise.then(function (val) {
                ctx.hasControversyClaim = val;
            });
        }

        private getControversiesFeatureUniverse(companyId:string): ng.IPromise<Company.CorporateDataExtendedDto> {
            var ctx = this;
            var def = ctx.$q.defer();

            ctx.CompanyService.getById(companyId, Common.AccountFeature.Controversies).then(
                function (company) {
                    ctx.isControversyActive = company.data.isEnabled;
                    def.resolve(company);
                },
                function (reason) {
                    def.reject(reason);
                });

            return def.promise;
        }

        private getControversyIndicators(): ng.IPromise<ControversyIndicatorDto[]> {
            var ctx = this;
            var promise = ctx.ControversiesService.getQualitativePerformance(ctx.$scope.currentCompany.id);

            promise.then(function (res) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        // clear dictionary
                        ctx.controversyIndicatorsDic = new Common.Dictionary<ControversyIndicatorDto[]>();

                        // set values
                        ctx.controversyIndicators = res;

                        // fill dictionary
                        $.each(ctx.controversyIndicators, function (index, ind) {
                            // get indicators by category
                            var lst: ControversyIndicatorDto[] = ctx.controversyIndicatorsDic.getValue(ind.answerCategory.toString());

                            // create indicators list
                            if (!lst) {
                                lst = new Array();
                                ctx.controversyIndicatorsDic.add(ind.answerCategory.toString(), lst);
                            }

                            // add indicator to list
                            lst.push(ind);
                        });
                    });
                });
            },(reason) => {

                    //if (reason.status == 404)
                    //{
                    //    if (reason.data.errCode !== null) {
                    //        ctx.notFoundMessage = reason.data.message;
                    //    }
                    //}

                    //if (reason.status == 401) {
                    //    ctx.noClaims = true;
                    //}

                ga('create', 'UA-4379897-6', {
                    'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                });

                ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: Qualitative Performance Controller -> Error loading Controversy Indicators' });
            });

            return promise;
        }

        // filter controversy indicators by category
        public getControversyIndicatorsByCategory(category: number): ControversyIndicatorDto[] {
            var ctx = this;
            var categoryInd = ctx.controversyIndicatorsDic.getValue(category.toString());
            return categoryInd;
        }

        // get last category indicators
        public getControversyIndicatorsInLastCategory(): ControversyIndicatorDto[] {
            var ctx = this;
            var lastKey = ctx.getControversyIndicatorsLastCategory();
            if (!lastKey)
                return null;

            var indicators = ctx.controversyIndicatorsDic.getValue(lastKey.toString());
            return indicators;
        }

        // get last category
        public getControversyIndicatorsLastCategory(): number {
            var ctx = this;
            var keys = ctx.controversyIndicatorsDic.getKeys();
            if (!keys)
                return null;

            var lastKey = keys[keys.length - 1];
            return parseInt(lastKey) || 0;
        }

        // whether has indicators of specific category
        public hasControversyIndicatorsInCategory(category: number): boolean {
            var ctx = this;
            var indicators = ctx.getControversyIndicatorsByCategory(category);
            return indicators && indicators.length > 0;
        }

        public navigateToControversyIndicator(controversyIndicator: ControversyIndicatorDto) {
            var ctx = this;
            if (ctx.controversiesCtrl) {
                ctx.$rootScope['is_controversy_navigation'] = true;
                ctx.controversiesCtrl.goToControversyIndicator(controversyIndicator);
            }
            else {
                if (ctx.esgCtrl) {
                    ctx.$rootScope['is_controversy_navigation'] = true;
                    ctx.esgCtrl.goToControversyIndicator(controversyIndicator);
                }
            }
        }

        public navigateToEventIndicator(controversyIndicator: ControversyIndicatorDto, eventIndicator: EventIndicatorDto) {
            var ctx = this;
            if (ctx.controversiesCtrl) {
                ctx.$rootScope['is_controversy_navigation'] = true;
                ctx.controversiesCtrl.goToEventIndicator(controversyIndicator, eventIndicator);
            }
            else {
                if (ctx.esgCtrl) {
                    ctx.$rootScope['is_controversy_navigation'] = true;
                    ctx.esgCtrl.goToEventIndicator(controversyIndicator, eventIndicator);
                }
            }
        }

    }


    export var qualitativePerformanceControllerName = 'QualitativePerformanceController';

    angular.module(controversiesModuleName).controller(qualitativePerformanceControllerName,
        ['$rootScope', '$scope', '$q', '$timeout', '$filter', 'RoutingService', 'ControversiesService','CompanyService', QualitativePerformanceController]);
} 